package com.drcoffee.drcoffeemall.service.impl;

import com.drcoffee.drcoffeemall.entry.Document;
import com.drcoffee.drcoffeemall.mapper.DocumentMapper;
import com.drcoffee.drcoffeemall.service.DocumentService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class DocumentServiceImpl implements DocumentService {
    final
    DocumentMapper documentMapper;


    public DocumentServiceImpl(DocumentMapper documentMapper) {
        this.documentMapper = documentMapper;
    }

    @Override
    public Map<String, Object> getDocument(Integer machine_id, String search) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            List<Document> documentList;
            if (machine_id == null){
                documentList = documentMapper.getDocumentSearch('%' + search + '%');
            }else{
                documentList = documentMapper.getDocument(machine_id, '%' + search + '%');
            }
            resultMap.put("documentList", documentList);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("reason", e.toString());
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> getDocumentAll() {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            List<Document> documentList = documentMapper.getDocumentAll();
            resultMap.put("documentList", documentList);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("reason", e.toString());
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> addDocument(Document document) {
        Map<String, Object> resultMap = new HashMap<>();
//        document.setFile_path(data_img_init + document.getFile_path().replaceAll("\\\\", "/"));
        boolean result = documentMapper.addDocument(document);
        resultMap.put("result", result);
        if (result) {
            resultMap.put("message", "添加成功");
        } else {
            resultMap.put("message", "添加失败");
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> updateDocument(Document document) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            boolean result = documentMapper.updateDocument(document);
            resultMap.put("result", result);
            if (result){
                resultMap.put("message", "修改成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("reason", e.toString());
        }
        return resultMap;
    }
}
